import store from "@/store";
import {
  openNewPage,
  changeApp,
  changeOriginPageInApp,
  openWithMiddlePlatform,
  openDavinciWithMiddlePlatform,
  getImgfromApp,
  popOriginPage,
  _callApp,
} from "@/js/config/bridge.js";

import { Toast, Dialog } from "vant";

import axios from "./axios";

import Proconfig from "./config/proConfig";

import { APP_MIN_VERSION } from "@/store/global.js";

// @/assets/img/theameIcons/  目录下的图标名对应themeCode表
const iconNameTable = {
  ITEM_ADD: "item_add", // 添加主题
};
// 1.韵达大盘 2.服务质量 3.业务量 4.经营分析  5.省总KPI 6.网点运营 7.中转运营 8.时效分析  9.客户营销   10.事务流程   11.财务共享   12.信息查询
const bigThemeArr = {
  1: "bigTheme1",
  2: "bigTheme2",
  3: "bigTheme3",
  4: "bigTheme4",
  5: "bigTheme5",
  6: "bigTheme6",
  7: "bigTheme7",
  8: "bigTheme8",
  9: "bigTheme9",
  10: "bigTheme10",
  11: "bigTheme11",
  12: "bigTheme12",
};

function themeCodeToUpperCase(item) {
  if (item.themeCode) {
    item.themeCode = item.themeCode.toUpperCase();
  }
  return item;
}

export const iconInfo = (item) => {
  let defName = "def";

  item = themeCodeToUpperCase(item);
  if (iconNameTable[item.themeCode]) {
    defName = iconNameTable[item.themeCode];
  }
  let icon = require("@/assets/img/theameIcons/" + defName + ".png");
  return icon;
};

export const iconInfoBigTheme = (item) => {
  let defName = "def";

  if (bigThemeArr[item.busiSegm]) {
    defName = bigThemeArr[item.busiSegm];
  }
  let icon = require("@/assets/img/theameIcons/" + defName + ".png");
  return icon;
};

// 处理icon相关信息，策略： 优先本地，本地没有读后台配置的，后台没配置，默认的棕色图片
export const manageIconInfo = (item) => {
  item = themeCodeToUpperCase(item);
  if (item.children) {
    // 分组形式  大类
    item.localIcon = iconInfoBigTheme(item);
    for (const _t of item.children) {
      manageIconInfo(_t);
    }
  } else {
    // 自定义模式  每个主题
    if (iconNameTable[item.themeCode]) {
      item.localIcon = iconInfo(item);
    } else {
      if (item.icon?.length) {
        // 服务端返回的有icon
        item.remoteIcon = item.icon;
      } else {
        item.localIcon = iconInfo(item);
      }
    }
  }
};

// 已完成
export const finishedTheames = {
  // T116: "VolumeAndProfit", // 量&利日清   已使用最新的 基于指标的通用模板

  T117: "IndustryBenchmark", // 菜鸟质量对标
  T118: "ReportForm", // 网点揽派
  T105: "CommonTheme", // 三错
  T120: "CommonTheme", // 业务量
  T121: "CommonTheme", // 客户信息
  T112: "CommonTheme", // 服务及时率
  T104: "CommonTheme", // 全程时效
  T147: "BusinessComparison", // 快递业务量对标
  T148: "WeightRatio", // 揽派件业务量占比
  // T143: "CommonTheme", // 签收质量
  // T144: "CommonTheme", // 虚假签收
  T145: "CommonTheme", // 准备完整率
  T146: "CommonTheme", // 上传延时率
  T150: "ProfitAnalysis", // 获利能力
  T156: "TruckReport", // 班车运营报表
  T157: "ClientWarning", // 客户预警
  T119: "DistributedSiteKPI", // 分拨KPI
  T126: "FlowDirectionTheme", // 流量流向分享
  T159: "BookTakeSignTheme", // 订揽签报表
  T123: "CommonTheme", //三段码
  T160: "hrbi", // HRBI管理
  T161: "Stock", // 韵达大盘
  T170: "CommonTheme", // 返利
  T171: "CommonTheme", // "中转费其他"
  T172: "CommonTheme", // 截留
  T175: "CommonTheme", // "中转费"
  P101: "BusinessDetail", // ""操作费"" P101  T162
  // P104: 'BusinessDetail', // ""场地费"" P104  T163
  P107: "BusinessDetail", // ""中转费"" P107  T164
  P110: "BusinessDetail", // ""面单返利"" P110  T165
  P113: "BusinessDetail", // ""超区3+1"" P113  T166
  P116: "BusinessDetail", // ""客服"" P116  T167
  P119: "BusinessDetail", // ""扶持派费"" P119  T168
  // P122: 'BusinessDetail', // ""支线"" P122  T169

  T176: "DecisionHelper", // 决策辅助
  T177: "SheetType", // 面单类型
  T178: "StoreFine", // 网点罚款
  T179: "Licence", // 许可证报表
  T180: "AbnormalOrder", // 经营异常工单
  T134: "TransportCost", // 单公斤运输成本

  T182: "Zhangshangfenbo", // 掌上分拨
  T183: "ClientManage", // 商家管理
  T181: "ServiceQualityAssessment", // 服务质量考核
  T184: "CustomerComplaint", // 客诉质量

  T185: "IncomeAndExpenses", // 收支利
  T187: "PutTimelinessRate", //交件及时率
  T188: "ProcurationRecord", // 末端代收日志
  T196: "CloseDownStore", // 暂停网点报表
  T198: "StoreKPI", // 网点KPI

  T205: "FWelectriryRate", //电联率 -fuwu
  T209: "FWStoreCountList", //末端建设 -fuwu
  T202: "SurveyReport", // 调研报告
  T203: "ProvFbKPI", // 省&分拨KPI
  // T208: "OperateServiceQ", // 操作服务质量
  T206: "ZKProfit",
  T210: "Security", //安全
  T211: "AbnormalNode", //异常网点考核
  T212: "Priorities", //重点事项

  T236: "AccountsReceivable", // 直客应收账款
  T235: "DirectPassengerMaintenance", //直客获取维护
  T258: "StoreQuery", //网点信息查询
  // T265: "DeliveryCode", // 派送码末端码
  T265: "CommonTheme", // 派送码末端码

  T274: "SiftOrderMonitor", // 筛单异常监控
  T298: "mineJifen", // 我的积分

  T336: "LanPaiIndex", // 揽派对流,
  T363: "LanPaiHome", // 揽派对流主题页面
  T365: "LanPaiWpsNew", // 揽派对流wps
  T367: "lanpai2",

  T689: "GroupedThemes", // 客服整合-成本报表
  T690: "GroupedThemes", // 客服整合-遗失&破损
  T932: "AllCustomer", // 全行业全量客户清单
  T1013: "Dictionary", //指标字典
  T1043: "AllCustomerNew", // 全行业全量客户清单新
  T1049: "MustSee", //省区必看
  // T1044: "NetworkManageMustSee", // 网管必看
  T1069: "WeightReport",
  T1067: "MustSeeByGrid", // 网格长必看
  T1075: "NetworkTimeAssess", //网点时效考核
  T1080: "Contraband", //违禁品管控
  T1084: "TemplateIndex", //报表模版
  T1087: "SiteKPINew", // 网点KPI
  T1092: "EdgePriceWarn", //到边到角增长率
  T1097: "TodaySigned", //末端分拨当日到车件签收情况
  T1095: "AllCustomerDing", //全量客户钉钉
  T1098: "RealTickets", //分拨-票件实时跟踪
  T1090: "RecycleBag", //循环袋监控
  T1111: "GroupNonDing", //省区经营管家登录情况汇总
  T1165: "CrossValidation", //必跑省会分拨交叉验证
  T1168: "dingCheck", // 揽收超时工单测试(钉钉)
};

// 通用主题需要下钻页面的 主题code
export const commonThemeNeedNext = (
  themeCode,
  targetCode,
  exceptTargetCodes = []
) => {
  /**
   * 需要下钻的targetCode(或者themeCode)
   * 此处写的主题 没有适配其他角色，业务省角色 下钻到网点
   * CommmonThemeSuitPermission 适配了不同角色， 业务省角色-分拨-网点
   */
  let tmp = [
    "T123",
    "T120",
    // "T112",
    "E115",
    "E116",
    ...CommmonThemeSuitPermission,
  ];

  let flag = false;
  if (!exceptTargetCodes.includes(targetCode)) {
    if (tmp.includes(themeCode) || tmp.includes(targetCode)) {
      flag = true;
    }
  }

  return flag;
};

/**
 * 通用主题适配其他角色的code  （T120 业务量和实时业务量， 有单独判断的逻辑）
   分拨看城市列表
T112: "CommonTheme", // 服务及时率
T143: "CommonTheme", // 签收质量
T144: "CommonTheme", // 虚假签收
T145: "CommonTheme", // 准备完整率
T146: "CommonTheme", // 上传延时率
T123: "CommonTheme", // 三段码
 */
export const CommmonThemeSuitPermission = [
  // "T112",
  "T143",
  "T144",
  "T145",
  "T146",
  "T123",
  "T265",
  "T104",
];

// 通用主题  分拨角色看分拨列表的 指标code， themeCode先写到CommmonThemeSuitPermission数组， 指标code再写到此数组
export const CommmonThemeTargetFbRoleFbList = ["E115", "E116"];

// 通用主题无网点数据的主题编码（分拨页面不下钻到网点）
export const CommmonThemeNoStoreData = ["T265"];

// ========================================================================================
// 以指标为单位的主题（这种主题使用ThemeLayout布局，里面指标可以任意组合放到其他以ThemeLayout布局的主题）
const TargetUnitThemeCodes = [
  "T286",
  "T116",
  "T319",
  "T320",
  "T144",
  "T324",
  "T325",
  "T143", // 2022-05-05 签收质量 已经下架通用主题样式的指标，改为这种布局
  "T112", // 实效及时率
  "T339", // 直客实时量
  "T338",
  "T350",
  "T352",
  "T353",
  "T354",
  "T355",
  "T356", //分拨淡旺季
  "T357",
  "T359", //出货（轻小件）思维的揽派对流
  "T360", //本省各网点淡旺季出货政策和目标考核定价表
  "T362",
  "T381", // 重点报表-数据维护

  "T417", // 结算重量段
  "T431", // 实时揽件量

  "T447", // 大促货量预测
  "T446", //预警中心
  "T444", // 省总计分助手

  "T208", // 遗失破损

  "T459", // 抖音物流指数-接口
  "T471", //财务揽件一表通

  "T472", //发件成本
  "T485", // 报表模板
  "T488", // 全链路时长
  "T506", //菜鸟天地洞察数据
  "T695", //上传文件
  "T842", // 业务量-jy
  "T653", // 区县同行业务量月度环比
  "T888", // 业务量-网格长
  "T892", // 价格管理
  "T900", // 开班监控
  "T904", // 价格管理二期
  "T1014", // 预付款扣款账单
  "T1038", //拉粉列表
  "T1041", // 客户质量预警
  "T1044", // 网管必看
  "T1052", // 加盟网点经营分析表
  "T1059", // 客户质量预警
  "T1053", //培训赋能
  "T1060", //到边到角
  "T939", //报价过高预警
  "T1066", // 网格长必看
  "T1076", //班前例会
  "T1088", //物流评分低商家信息收集
  "T1091", // 春节运营保障
  "T1083", //协议/非协议客户信息
  "T1103", //费率设置监控
];

const routerNameByTheameCode = (themeCode) => {
  let name = "404";
  if (TargetUnitThemeCodes.includes(themeCode)) {
    return "ThemeLayout";
  }

  for (const key in finishedTheames) {
    if (themeCode === key) {
      return finishedTheames[key];
    }
  }
  return name;
};
function track(event, item) {
  if (window.sensors) {
    window.sensors.quick(
      "trackHeatMap",
      event.target,
      {
        themeCode: item.themeCode, //如果需要添加自定义属性需要将 SDK 升级到 1.13.7 及以上版本。
        themeName: item.themeName,
      },
      function () {
        console.log("sensor callback");
      }
    );
  }
}

/**
 * 点击主题   页面跳转
 * @param {*} item 主题对象 {themeCode: 'aaa', themeName: 'xxx'}
 * @param {*} thisValue thisValue 当前调用的vue对象
 * @param {*} readCallBack readCallBack 已读回调
 * @param {*} otherQuery otherQuery 其他查询字符串 {defTgtCode, type, index }
 * @param {*} replace replace 是否已replace的方式跳转
 * @param {*} event 神策定义的事件
 */
export const pushPage = async (
  item,
  thisValue,
  readCallBack,
  otherQuery,
  replace = false,
  event
) => {
  console.log("pushPage item", item);
  // alert(JSON.stringify(item))

  if (event) {
    track(event, item);
  }
  if (window.sensors) {
    if (item.themeName) {
      let category = `省区经营管家|${item.themeName}|${item.themeName}`;
      window.sensors.registerPage({
        category,
      });
      sensors.quick("autoTrackSinglePage");
    }
  }
  item = themeCodeToUpperCase(item);
  let _numSource = Number(item.source);
  if (isNaN(_numSource)) {
    _numSource = 0;
  }
  item.source = _numSource;

  if (item?.url) {
    item.url = item.url.replace(/\s+/g, ""); // 去掉url里面的空格
  }

  let token = store.state.global.loginInfo.token || "";
  let empCode = store.state.global.loginInfo.empCode || "";
  store.commit("global/setThemeCode", item.themeCode);
  // alert("push" + JSON.stringify(store.state.global.loginInfo));

  if (!token || !empCode) {
    try {
      const res = await getLoginInfo();
      if (res) {
        token = res.token;
        empCode = res.empCode;
      }
    } catch (error) {}
  }

  // store.dispatch("global/getRoleLevel",{themeCode:item.themeCode})

  let name = routerNameByTheameCode(item.themeCode);
  if (item.source == "0" && item.url) {
    name = item.url;
  }
  /**
   * 魔术变量
   * 特定变量名： 动态获取变量值
   * "@NEED_DEFAULT_VARS"  是否需要默认的 参数（fromAppCode, empCode, token）
   */
  const MAGIC_VARS = {
    "@EMP_CODE": empCode,
    "@TOKEN": token,
  };

  const magicKeys = Object.keys(MAGIC_VARS);

  if (item.isNew === "yes") {
    // 新主题
    thisValue.$axios
      .sendGateWay({
        action: "ydCommanderReport.v1.theme.firstOperateLog",
        data: {
          themeCode: item.themeCode,
        },
      })
      .then((res) => {
        if (res.body && res.body.code == "SUCCESS") {
          item.isNew = "no";
          if (readCallBack) {
            readCallBack();
          }
        }
      });
  }

  // source：0：内部，1：外部(和内部相同的webview)   2weex模块   3原生SDK   4唤醒app  5外部（使用中台容器） 6davinci 7davinci中台-内部 8davinci中台-外部

  const { params, _passedParams } = item;
  let _optParams = {};
  if (isJSON(params)) {
    _optParams = JSON.parse(params);
  }
  let ticket = "";
  if (!Proconfig.wtModel && [1, 3, 4, 5, 6, 7, 8].includes(item.source)) {
    let response = await axios.sendGateWay({
      action: "ydCommanderAuth.v1.auth.api.createTicket",
      data: {},
    });
    if (response.errorcode === "SUCCESS") {
      let data = response.body.data;
      ticket = data.ticket;
      console.log("ticket---", data.ticket);
    } else {
      setTimeout(() => {
        Toast("请稍后再次尝试");
      }, 300);
      return;
    }
  }

  if (!Proconfig.wtModel && [1, 3, 4, 5, 6, 7, 8].includes(item.source)) {
    if (item.pcUrl) {
      // web端跳转
      let pcUrl = item.pcUrl;
      let params = item.pcParams?.split("|") ?? [];
      if (params.includes("token")) {
        pcUrl =
          item.pcUrl.indexOf("?") == -1
            ? `${item.pcUrl}?token=${token}&ticket=${ticket}`
            : `${item.pcUrl}&token=${token}&ticket=${ticket}`;
      }
      params.includes("_blank")
        ? window.open(pcUrl, "_blank")
        : (window.location.href = pcUrl);
    } else {
      setTimeout(() => {
        Toast("未接入PC，请访问移动端");
      }, 300);
    }
    return;
  }

  if (item.source == 1) {
    let _defaultVars = { fromAppCode: "gxt", empCode, token };
    if (item.themeCode == "T1035") {
      let response = await axios.sendGateWay({
        action: "ydCommanderReport.v1.ydgpt.auth.getTokenRobot",
        data: {
          systemId: "sqjygj",
          orgId: "1000001",
          accountId: empCode,
        },
      });
      if (response.errorcode === "SUCCESS") {
        let token = response.body.data;
        _defaultVars = {
          systemId: "sqjygj",
          orgId: "1000001",
          fromAppCode: "gxt",
          accountId: empCode,
          token,
          type: 4,
          secret: "71a6f77b3e6f005f",
        };
      } else {
        Toast.fail("请稍后再次尝试");
        return;
      }
    }
    if (+_optParams["@NEED_DEFAULT_VARS"] == 0) {
      // 不需要默认参数
      _defaultVars = {};
    }

    for (const key in _optParams) {
      if (Object.hasOwnProperty.call(_optParams, key)) {
        const element = _optParams[key];
        if (magicKeys.includes(element)) {
          _defaultVars[key] = MAGIC_VARS[element];
        }
      }
    }

    if (otherQuery) {
      _defaultVars = {
        ..._defaultVars,
        ...otherQuery,
      };
    }

    if (_passedParams) {
      _defaultVars = {
        ..._defaultVars,
        ..._passedParams,
      };
    }
    _defaultVars = {
      ..._defaultVars,
      ticket,
    };
    let url = processURL(item.url, _defaultVars);
    // console.log("source 1: ", url);

    let obj = { url };
    obj.needAppReplace = item.needAppReplace;

    if (Reflect.has(item, "showTitle")) {
      obj.isShowNavBar = item.showTitle;
    }
    if (item.isShowBreadcrumb == 0 || item.isShowBreadcrumb == 1) {
      obj.isShowBreadcrumb = item.isShowBreadcrumb;
    }

    if (item.showTitle) {
      // 外部链接时  原生新页面是否显示导航栏及标题
      obj.title = item.themeName;
    }
    if (item.themeCode === "") {
    }
    openNewPage(obj);
  } else if (item.source == 3) {
    // 原生页面跳转
    if (item.url?.length) {
      let themeObj = {
        themeCode: item.themeCode,
        themeName: item.themeName,
      };

      if (item._passedParams) {
        // 下钻时传递的参数 直接放到themeObj
        themeObj = {
          ...themeObj,
          ...item._passedParams,
        };
      }

      if (Object.keys(_optParams).length) {
        themeObj.configParams = _optParams;
      }

      themeObj.needAppReplace = item.needAppReplace;
      changeOriginPageInApp(item.url, themeObj);
    }
  } else if (item.source == 4) {
    // 唤醒App
    if (item.url?.length) {
      changeApp(item.url);
    }
  } else if (item.source == 5) {
    // 外部链接  中台容器打开

    const { themeName, routerName } = item;

    if (!Proconfig.wtModel && item.themeCode == "T875") {
      // 临时支持全链路发签卡点零缺陷跳转
      let url =
        process.env.VUE_APP_PROD == "1"
          ? `http://det.yundasys.com:30213/#/data/view/fullLink/index?redirect=1`
          : `http://10.171.149.243:30213/#/data/view/fullLink/index?redirect=1`;
      window.location.href = url;
      return;
    }

    // if (Proconfig.wtModel) {
    //   // 梧桐模式
    //   thisValue.$ydcommon.push(routerName, _optParams, function (e) {});
    // } else {

    let url = item.url;

    if (item.themeCode == "T1113") {
      // 临时增加token参数
      let _defaultVars = { fromAppCode: "gxt", empCode, token };
      url = processURL(item.url, _defaultVars);
    }

    console.log(99999, url);

    let param = {
      isShowNavBar: item.showTitle,
      title: themeName,
      name: routerName,
      url: url,
      ..._optParams,
    };
    if (item.showTitle) {
      // 外部链接时  原生新页面是否显示导航栏及标题
      param.title = item.themeName;
    }
    if (item.isShowBreadcrumb == 0 || item.isShowBreadcrumb == 1) {
      param.isShowBreadcrumb = item.isShowBreadcrumb;
    }

    param.needAppReplace = item.needAppReplace;
    openWithMiddlePlatform(param);
    // }
  } else if ([6, 7, 8].includes(item.source)) {
    // davinci

    axios
      .sendGateWay({
        action: "ydCommanderReport.v1.davinci.getToken",
        data: {
          source: item.source,
          themeCode: item.themeCode,
        },
      })
      .then((res) => {
        // console.log(res);

        if (res.body && res.body.code == "SUCCESS") {
          let dToken = res.body.data;
          if (dToken && dToken.length) {
            if (item.source == 6) {
              // 以外部链接形式打开 davinci
              let url = item.url;
              // if (url.indexOf("?") != -1) {
              //   url = `${url}&token=${dToken}`;
              // } else {
              //   url = `${url}?token=${dToken}`;
              // }

              url = url.replace("share.html", "index.html");
              //  问号后面 拼接token=xxx&
              if (url.indexOf("?") != -1) {
                // 问号后面 拼接token=xxx&
                url = url.replace("?", `?token=${dToken}&`);
              } else {
                url = `${url}?token=${dToken}`;
              }

              // console.log(url);
              let obj = { url, isShowNavBar: item.showTitle };

              if (item.showTitle) {
                // 外部链接时  原生新页面是否显示导航栏及标题
                obj.title = item.themeName;
              }
              if (item.isShowBreadcrumb == 0 || item.isShowBreadcrumb == 1) {
                obj.isShowBreadcrumb = item.isShowBreadcrumb;
              }

              obj.needAppReplace = item.needAppReplace;
              openNewPage(obj);
            }

            let param = {
              url: item.url,
              token: dToken,
              appToken: token,
              from: "gxt",
              isShowNavBar: item.showTitle,
              needAppReplace: item.needAppReplace,
            };
            if (item.isShowBreadcrumb == 0 || item.isShowBreadcrumb == 1) {
              param.isShowBreadcrumb = item.isShowBreadcrumb;
            }
            if (item.showTitle) {
              // 外部链接时  原生新页面是否显示导航栏及标题
              param.title = item.themeName;
            }

            if (item.source == 7) {
              // 使用中台容器打开
              openDavinciWithMiddlePlatform(param);
            }
            if (item.source == 8) {
              // 使用中台容器打开-外部
              openDavinciWithMiddlePlatform(param, "gxt-davinci-open");
            }
          } else {
            Toast.fail("未获取到自助平台token，请联系管理员或者稍后重试");
          }
        } else {
          Toast.fail("未获取到自助平台token，请联系管理员或者稍后重试");
        }
      });
  } else {
    if (name == "404") {
      const jqqd = "敬请期待";
      thisValue.$notify({
        message: jqqd,
        color: "#fff",
        background: "rgba(0,0,0,0.5)",
        duration: 1000,
      });
      thisValue.$router.push({
        name: "404",
        query: { title: jqqd, tip: jqqd, breadName: jqqd, ...otherQuery },
      });
      return;
    }
    const { themeCode } = thisValue.$route.query;

    if (!item?._passedParams?._forcePush && themeCode == item.themeCode) {
      // 已经是当前主题  不做跳转
      console.log("########当前已经是此主题，不做跳转");
      return;
    }

    let query = {
      themeCode: item.themeCode,
      themeName: item.themeName,
      params: item.params,
    };
    if (otherQuery) {
      query = {
        ...query,
        ...otherQuery,
      };
    }

    if (query.themeCode.toUpperCase() == "T120" && query.type !== "realTime") {
      // 实时业务量  老版首页用index来区分默认指标
      query["defTgtCode"] = "M104";
    }

    const routeParams = item._passedParams ?? {};

    if (replace) {
      thisValue.$router.replace({
        name,
        query,
        params: routeParams,
      });
    } else {
      thisValue.$router.push({
        name,
        query,
        params: routeParams,
      });
    }
  }
};

export const processURL = (originURL, otherQuery = {}) => {
  // console.log("originURL", originURL);
  // console.log("otherQuery", otherQuery);

  let _search = "";
  for (const key in otherQuery) {
    if (Object.hasOwnProperty.call(otherQuery, key)) {
      if (_search.length) {
        _search += "&";
      }
      const element = otherQuery[key];
      _search += `${key}=${element}`;
    }
  }
  let res = originURL;

  if (_search.length) {
    if (originURL.includes("?")) {
      res = res + "&" + _search;
    } else {
      res = res + "?" + _search;
    }
  }

  // console.log("res", res);
  return res;
};

export const getLoginInfo = () => {
  return new Promise((resolve, reject) => {
    if (!Proconfig.wtModel) {
      reject();
    }

    window.yjsBridge.call("appToken.appToken", {}, async function (res) {
      const obj = json2Obj(res);
      if (obj) {
        const { from } = obj;
        // alert("from:::::" + from);
        if (from != "gxt") {
          reject();
        }

        const token = store.state.global.loginInfo.token;
        const empCode = store.state.global.loginInfo.empCode;
        if (!token || !empCode) {
          const res = await _callApp({ actionID: 1 });
          await store.commit("global/setLoginInfo", res);
          await store.dispatch("global/getRoleList");
          // await store.dispatch("global/getNewPage");
          resolve(res);
        }
        resolve(store.state.global.loginInfo);
      } else {
        reject();
      }
    });
  });
};

// 浅复制，只做第一层复制
export const shallowCopy = (src) => {
  var dst = {};
  for (var prop in src) {
    if (src.hasOwnProperty(prop)) {
      dst[prop] = src[prop];
    }
  }
  if (Object.prototype.toString.call(src) == "[object Array]") {
    dst = Object.values(dst);
  }
  return dst;
};

/**
 * 深拷贝
 * @param {*} obj 拷贝对象(object or array)
 * @param {*} cache 缓存数组
 */
export const deepCopy = (obj, cache = []) => {
  // typeof [] => 'object'
  // typeof {} => 'object'
  if (obj === null || typeof obj !== "object") {
    return obj;
  }
  // 如果传入的对象与缓存的相等, 则递归结束, 这样防止循环
  /**
   * 类似下面这种
   * var a = {b:1}
   * a.c = a
   * 资料: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Cyclic_object_value
   */
  const hit = cache.filter((c) => c.original === obj)[0];
  if (hit) {
    return hit.copy;
  }

  const copy = Array.isArray(obj) ? [] : {};
  // 将copy首先放入cache, 因为我们需要在递归deepCopy的时候引用它
  cache.push({
    original: obj,
    copy,
  });
  Object.keys(obj).forEach((key) => {
    copy[key] = deepCopy(obj[key], cache);
  });

  return copy;
};

// 合并大区里省份的coordinates
export const mergeProvinces = (chinaJson, names, properties) => {
  var features = chinaJson.features;
  var polygons = [];

  for (var i = 0; i < names.length; i++) {
    var polygonsCoordinates = [];
    for (var z = 0; z < names[i].length; z++) {
      for (var j = 0; j < features.length; j++) {
        if (features[j].properties.name == names[i][z]) {
          // 合并coordinates
          if (features[j].geometry.coordinates[0].constructor == String) {
            for (var l = 0; l < features[j].geometry.coordinates.length; l++) {
              polygonsCoordinates.push(features[j].geometry.coordinates[l]);
            }
          } else if (features[j].geometry.coordinates[0].constructor == Array) {
            for (var k = 0; k < features[j].geometry.coordinates.length; k++) {
              for (
                var d = 0;
                d < features[j].geometry.coordinates[k].length;
                d++
              ) {
                polygonsCoordinates.push(
                  features[j].geometry.coordinates[k][d]
                );
              }
            }
          }
          // 原数组 移除合并的
          features.splice(j, 1);
          break;
        }
      }
    }
    polygons.push(polygonsCoordinates);
  }

  // 构建新的合并区域
  var temp = [];

  for (var a = 0; a < names.length; a++) {
    var feature = {
      id: temp.length.toString(),
      type: "FeatureCollection",
      geometry: {
        type: "Polygon",
        coordinates: polygons[a],
      },
      properties: {
        name: properties.name[a] || "",
        childNum: polygons[a].length,
      },
    };
    if (properties.cp[a]) {
      feature.properties.cp = properties.cp[a];
    }

    // 将新的合并区域添加到地图中
    temp.push(feature);
  }
  chinaJson.features = features.concat(temp);
};

export const textColorByValue = (
  value,
  redColor = "#FF3535",
  greenColor = "#348B1A"
) => {
  let v = Number(value);
  if (value && v) {
    if (v > 0) {
      return redColor; // 红色
    }
  }
  return greenColor; // 绿色
};

// 转换数值信息， 超过10000 显示万， 超过一亿显示亿
export const showNumInfo = (oldVal, fixedNum = 2, absVal = false, unitCfg) => {
  let val = getNumVal(oldVal, absVal);

  const wan = 10000;
  const yi = 100000000;

  let _wanUnit = "万";
  let _yiUnit = "亿";
  if (unitCfg) {
    const { wanUnit = _wanUnit, yiUnit = _yiUnit } = unitCfg;
    _wanUnit = wanUnit;
    _yiUnit = yiUnit;
  }

  let unit = "";
  if (val > wan) {
    val = val / wan;
    unit = _wanUnit;
  }
  if (val > yi) {
    val = val / yi;
    unit = _yiUnit;
  }
  val = roundNum(val, fixedNum);
  return val + unit;
};
//转换万 w
export const showFWUnit = (oldVal, fixedNum = 2, absVal = false, unitCfg) => {
  let val = getNumVal(oldVal, absVal);

  const wan = 10000;
  const yi = 100000000;

  let _wanUnit = "w";
  let _yiUnit = "y";
  if (unitCfg) {
    const { wanUnit = _wanUnit, yiUnit = _yiUnit } = unitCfg;
    _wanUnit = wanUnit;
    _yiUnit = yiUnit;
  }

  let unit = "";
  if (val > wan) {
    val = val / wan;
    unit = _wanUnit;
  }
  if (val > yi) {
    val = val / yi;
    unit = _yiUnit;
  }
  val = roundNum(val, fixedNum);
  return val + unit;
};
// 获得数值 空为0
export const getNumVal = (v, absVal = false) => {
  if (v && Number(v)) {
    let val = Number(v);
    if (absVal) {
      val = Math.abs(val);
    }
    return val;
  }
  return 0;
};

// 取val， 空转为 -
export const showInfo = (v, def = "-") => {
  let t = def;

  let type = typeof v;
  // console.log("type", type);
  if (type == "string") {
    if (v.length) {
      t = v;
    }
  } else if (v || v === 0) {
    t = v;
  }
  return t;
};

// 表头展示 名称和单位
export const showInfoUnit = (info, unit, wrpperUnit = true) => {
  let r = "-";
  if (info) {
    r = info;
  }
  if (unit && unit.length) {
    if (wrpperUnit) {
      r += `(${unit})`;
    } else {
      r += `${unit}`;
    }
  }
  return r;
};

// 格式化数字， 空转为 -
export const formatNum = (v, ignoreLastZeroAfterDot = false) => {
  let res = "-";
  if (typeof v == "string") {
    if (v.length == 0) {
      return res;
    }
    if (v == "Infinity") {
      return res;
    }
  }

  if (v == 0) {
    res = v.toString();
    return res;
  }

  if (v) {
    let a = Number(v);
    if (a) {
      res = a.toString();
    }
  }

  if (ignoreLastZeroAfterDot) {
    let _numV = Number(res);
    if (_numV) {
      _numV = _numV / 1; // 去掉小数点后 末位的 0
    } else {
      _numV = 0;
    }
    res = _numV.toString();
  }

  return res;
};
// 格式化率值数字
export const formatRatioNum = (
  v,
  unit = "%",
  appendUnit = true,
  fixedNum = 1
) => {
  let r = "-";
  if (typeof v == "string" && v.length) {
    let reg = /(^0*$)|(^0*\.$)|(^0*\.0*$)/; // 全为0 或者 0和一个.
    if (reg.test(v)) {
      // 2020-10-19 17:59:50 这种情况 改为 直接显示 0
      // r = v;
      r = "0";
      if (appendUnit) {
        r += unit;
      }
      return r;
    }
  } else if (typeof v == "number") {
    if (v == 0) {
      v = "0";

      r = v.toString();
      if (appendUnit) {
        r += unit;
      }
      return r;
    }
  }

  if (!(v && Number(v))) {
    if (appendUnit) {
      r += unit;
    }
    return r;
  }

  let _v = Number(v);
  if (unit == "%") {
    r = roundNum(_v * 100, fixedNum);
  }

  if (unit == "‰") {
    r = roundNum(_v * 1000, fixedNum);
  }

  if (unit == "‱") {
    r = roundNum(_v * 10000, fixedNum);
  }

  if (appendUnit) {
    r += unit;
  }

  return r;
};
// 格式化率值数字
export const formatRatioNum2 = (
  v,
  unit = "%",
  appendUnit = true,
  fixedNum = 1
) => {
  let r = "-";
  if (typeof v == "string" && v.length) {
    let reg = /(^0*$)|(^0*\.$)|(^0*\.0*$)/; // 全为0 或者 0和一个.
    if (reg.test(v)) {
      // 2020-10-19 17:59:50 这种情况 改为 直接显示 0
      // r = v;
      r = "0";
      if (appendUnit) {
        r += unit;
      }
      return r;
    }
  } else if (typeof v == "number") {
    if (v == 0) {
      v = "0";

      r = v.toString();
      if (appendUnit) {
        r += unit;
      }
      return r;
    }
  }

  if (!(v && Number(v))) {
    if (appendUnit) {
      r += unit;
    }
    return r;
  }

  let _v = Number(v);
  if (unit == "%") {
    r = roundNum(_v * 100, fixedNum);
  }

  if (unit == "‰") {
    r = roundNum(_v * 1000, fixedNum);
  }

  if (unit == "‱") {
    r = roundNum(_v * 10000, fixedNum);
  }

  if (appendUnit) {
    r += unit;
  }

  return r;
};

// 四舍五入保留n位小数，最后/1或者*1, 表示小数点末位的0 省略
export const roundNum = (num, n = 1, ignoreLastZeroAfterDot = false) => {
  let _tmpNum = formatNum(num);
  let _numVal = Number(_tmpNum);

  if (_numVal == 0 || _numVal) {
    let sign = 1;
    if (_numVal < 0) {
      sign = -1;
      _numVal = Math.abs(_numVal);
    }

    let s = Math.pow(10, n);

    if (ignoreLastZeroAfterDot) {
      return (sign * (Math.round(_numVal * s) / s).toFixed(n)) / 1;
    }
    return sign * (Math.round(_numVal * s) / s).toFixed(n);
  }

  return _tmpNum;
};

// 获取通用主题指标的 数值和单位
export const showCommonThemeInfo = (o = {}, key, unitObj, targetCode) => {
  let unit = "";
  let val = o[key] || "-";

  const must = ["prevRingRatio"];

  const arr = ["actualVal", "targetVal", "diffVal", "prevActualVal"];
  const _fixed4Arr = ["S208", "S215"]; // 这些指标  百分比保留3位小数

  // if (toString.call(o) !== "[object Object]" || !o.hasOwnProperty('numType')) {
  // }
  if (must.includes(key)) {
    unit = "%";
    val = formatRatioNum(val, unit, false);
  } else if (o.numType == "ratio") {
    if (arr.includes(key)) {
      let fixedNum = 1;
      if (targetCode && _fixed4Arr.includes(targetCode)) {
        fixedNum = 4;
      }
      unit = "%";

      val = formatRatioNum(val, unit, false, fixedNum);
    } else {
      if (unitObj) {
        unit = unitObj[key];
      }
      val = formatNum(val, true);
    }
  } else {
    if (unitObj) {
      unit = unitObj[key];
    }
    val = formatNum(val, true);
  }
  return {
    val,
    unit,
  };
};

/**
 * 转换AreaDateFilterTool通用筛选工具dateType， 为接口需要的type
 */
export const transformFilterDateType = (type) => {
  let r = "d";
  switch (type) {
    case "day":
      r = "d";
      break;
    case "asyncDay":
      r = "d";
      break;
    case "month":
      r = "m";
      break;
    case "season":
      r = "q";
      break;
    case "year":
      r = "y";
      break;
    default:
      break;
  }
  return r;
};

/**
 * 转换AreaDateFilterTool通用筛选工具dateType， 为接口需要的type, 数字形式  日1 月3 季4 年5
 */
export const transformFilterDateNumType = (type) => {
  let r = 1;
  switch (type) {
    case "day":
      r = 1;
      break;
    case "asyncDay":
      r = "1";
      break;
    case "month":
      r = 3;
      break;
    case "season":
      r = 4;
      break;
    case "year":
      r = 5;
      break;
    default:
      break;
  }
  return r;
};

export const getAllImgs = (content) => {
  const imgReg = /<img\b.*?(?:\>|\/>)/gi;
  return content.match(imgReg);
};

export const getImgSrc = (content) => {
  // const srcReg = /\bsrc\b\s*=\s*[\'\"]?([^\'\"]*)[\'\"]?/i;
  // return content.match(srcReg)

  let eleTmp = document.createElement("div");
  eleTmp.innerHTML = content;
  var imgSrc = eleTmp.childNodes[0].src;
  eleTmp.remove();
  return imgSrc;
};

/**
 * 根据文件名转换为可以访问的URL
 * @param {*} fileName 文件名
 */
export const mapFileUrl = async (
  fileName,
  base = "/cptFileProxy",
  needToken = false,
  complateUrl = false,
  asyncTest = false
) => {
  const token = store.state.global.loginInfo.token || "";

  // let url = complateUrl
  //   ? fileName
  //   : base + "/v1/common/downloadFile?" + "filePath=" + fileName;
  let url = fileName;
  if (needToken && token && token.length) {
    url += "?ydCommanderAuthToken=" + token;
  }

  if (Proconfig.wtModel) {
    // let { filePath } = await getImgfromApp({ imageUrl: url }, asyncTest);

    // return filePath;
    return url;
  } else if (fileName) {
    return url;
  } else {
    return "-";
  }
};

export function validStringNotEmpty(str) {
  if (str && str.length) {
    return str.trim().length > 0;
  }
  return false;
}

/**
 * @desc 函数防抖
 * @param func 函数
 * @param wait 延迟执行毫秒数
 * @param immediate true 表立即执行，false 表非立即执行
 */
export function debounce(func, wait, immediate) {
  var timeout;
  return function () {
    let context = this;
    let args = arguments;

    if (timeout) clearTimeout(timeout);
    if (immediate) {
      var callNow = !timeout;
      timeout = setTimeout(() => {
        timeout = null;
      }, wait);
      if (callNow) func.apply(context, args);
    } else {
      timeout = setTimeout(function () {
        func.apply(context, args);
      }, wait);
    }
  };
}

/**
 * @desc 函数节流
 * @param func 函数
 * @param wait 延迟执行毫秒数
 * @param type 1 表时间戳版，2 表定时器版
 */
export function throttle(func, wait, type) {
  if (type === 1) {
    var previous = 0;
  } else if (type === 2) {
    var timeout;
  }
  return function () {
    let context = this;
    let args = arguments;
    if (type === 1) {
      let now = Date.now();

      if (now - previous > wait) {
        func.apply(context, args);
        previous = now;
      }
    } else if (type === 2) {
      if (!timeout) {
        timeout = setTimeout(() => {
          timeout = null;
          func.apply(context, args);
        }, wait);
      }
    }
  };
}

export const isNotEmptyOrNull = (value) => {
  return value !== null && value !== undefined && value !== "";
};

/**
 * 提示东莞错误提示
 */
export function showErrowProvice(thisValue) {
  thisValue.$toast("2020年7月10日后，东莞已合并至广州");
}

/**
 * 获取上期值 名称
 */
export const getLastName = (reqParam) => {
  let lastName = "-";
  if (reqParam.dateType == "d") {
    lastName = "昨日";
    if (reqParam.endDt !== reqParam.startDt) {
      lastName = "上期";
    }
  }
  if (reqParam.dateType == "w") {
    lastName = "上周";
  }
  if (reqParam.dateType == "m") {
    lastName = "上月";
  }
  if (reqParam.dateType == "q") {
    lastName = "上季";
  }
  if (reqParam.dateType == "y") {
    lastName = "去年";
  }
  return lastName;
};

/**
 *
 * @param {日期类型 d  m  q  y} dateType
 * @param {是否是 当日 当月 当季 当年} isCurrent
 * @param {是否使用默认的 “值”} useDefValName
 * @returns 上期值的字符串
 */

export function getPreTitle(dateType, isCurrent, useDefValName = true) {
  let _defValName = "值";
  let r = "上期";
  switch (dateType) {
    case "d":
      {
        if (isCurrent) {
          r = "昨日";
        }
      }
      break;
    case "w":
      {
        r = "上周";
      }
      break;
    case "m":
      {
        r = "上月";
      }
      break;
    case "q":
      {
        r = "上季";
      }
      break;
    case "y":
      {
        r = "去年";
      }
      break;
    default:
      break;
  }

  if (useDefValName) {
    r = r + _defValName;
  }
  return r;
}
export function str1endWithStr2(str1, str2) {
  var d = str1.length - str2.length;
  return d >= 0 && str1.lastIndexOf(str2) == d;
}
// 带分拨的四级筛选器  转换参数
export function transformAreaParamForAllocatingCenterPicker(
  site,
  useCode2 = false
) {
  let p = {};
  if (!site) {
    return p;
  }
  const { siteLevel, siteId, siteId2 } = site;

  if (siteLevel == 0) {
    p.areaId = null;
    p.provId = null;
    p.fbId = null;
  } else if (siteLevel == 1) {
    p.areaId = siteId;
    if (useCode2 && siteId2) {
      p.areaId = siteId2;
      p.gxtAreaId = siteId;
      p.baseAreaId = siteId2;
    }
    p.provId = null;
    p.fbId = null;
  } else if (siteLevel == 2) {
    p.areaId = null;
    p.provId = siteId;
    p.fbId = null;
  } else if (siteLevel == 3) {
    p.areaId = null;
    p.provId = null;
    p.fbId = siteId;
  } else if (siteLevel == 7) {
    p.areaId = null;
    p.provId = null;
    p.fbId = siteId;
  }
  return p;
}
// 带分拨的四级筛选器  转换参数 人资必看
export function transformAreaParamForAllocatingCenterPickerRZ(
  site,
  useCode2 = false
) {
  let p = {};
  if (!site) {
    return p;
  }
  const { siteLevel, siteId, siteId2 } = site;

  if (siteLevel == 1) {
    p.areaId = null;
    p.provId = null;
    p.fbId = null;
  } else if (siteLevel == 2) {
    p.areaId = siteId;
    if (useCode2 && siteId2) {
      p.areaId = siteId2;
      p.gxtAreaId = siteId;
      p.baseAreaId = siteId2;
    }
    p.provId = null;
    p.fbId = null;
  } else if (siteLevel == 3) {
    p.areaId = null;
    p.provId = siteId;
    p.fbId = null;
  } else if (siteLevel == 4) {
    p.areaId = null;
    p.provId = null;
    p.fbId = siteId;
  }
  return p;
}
// 三级筛选 转换成 四级的形式
export function transformAreaParamToAllocatingCenterPicker(param) {
  let p = {};
  const { areaId, provId, fbId } = param;
  if (!areaId && !provId && !fbId) {
    p.code = 0;
    p.level = 0;
  } else {
    if (areaId && !provId && !fbId) {
      p.code = areaId;
      p.level = 1;
    } else if (provId && !fbId) {
      p.code = provId;
      p.level = 2;
    } else if (fbId) {
      p.code = fbId;
      p.level = 3;
    }
  }
  return p;
}

/**
 *
 * @param {*} 待解析的url
 * @param {*} 是否对url接码
 * @param {*} 是否去掉文件名后面拼接的时间戳
 * @returns
 */
export const getFileNameByUrl = (
  url,
  urlDecode = false,
  excludeTimestamp = false
) => {
  let res = url;

  if (urlDecode) {
    url = decodeURIComponent(url);
  }

  if (excludeTimestamp) {
    // 去掉 文件名后面的时间戳
    let _reg = /_\d{13}\./g;
    let _rArr = url.match(_reg);
    if (_rArr?.length) {
      let _timestamp = _rArr[_rArr.length - 1];
      let arr = url.split(_timestamp);
      res = arr.join(".");
    }
  }

  let tmp = res?.split("/");
  if (tmp?.length) {
    res = tmp[tmp.length - 1];
  }

  return res;
};

export function isJSON(str) {
  if (typeof str == "string") {
    try {
      var obj = JSON.parse(str);

      if (typeof obj == "object" && obj) {
        return true;
      } else {
        return false;
      }
    } catch (e) {
      console.log("error：" + str + "!!!" + e);
      return false;
    }
  }
  // console.log("It is not a string!");
}

export function json2Obj(origin) {
  if (isJSON(origin)) {
    return JSON.parse(origin);
  }
  return origin;
}

// 'get-element-by-id'=>'getElementById'
export function getCamelCase(str) {
  // debugger
  var arr = str.split("_");
  return arr
    .map(function (item, index) {
      if (index === 0) {
        return item;
      } else {
        return item.charAt(0).toUpperCase() + item.slice(1);
      }
    })
    .join("");
}
/*
 * 驼峰转换下划线
 */
export function humpToUnderline(str) {
  let temp = str.replace(/[A-Z]/g, function (match) {
    return "_" + match.toLowerCase();
  });
  // 如果首字母是大写，执行replace时会多一个_，这里需要去掉
  if (temp.slice(0, 1) === "_") {
    temp = temp.slice(1);
  }
  return temp;
}
// JSON对象的key值转换为驼峰式
export function jsonToHump(obj) {
  // debugger
  if (obj instanceof Array) {
    obj.forEach(function (v, i) {
      jsonToHump(v);
    });
  } else if (obj instanceof Object) {
    Object.keys(obj).forEach(function (key) {
      var newKey = getCamelCase(key);
      if (newKey !== key) {
        obj[newKey] = obj[key];
        delete obj[key];
      }
      jsonToHump(obj[newKey]);
    });
  }
  console.log("obj", obj);
}
export function changeSingleArrToDouble(arr, size) {
  if (!arr?.length) return [];
  let sliders = [];
  size = size ? size : 6;
  const total = Math.ceil(arr.length / size); // 总页数

  for (let i = 0; i < total; i++) {
    const t = arr.slice(i * size, (i + 1) * size); // 0-4
    sliders.push(t);
  }
  // console.log("sliders", sliders);
  return sliders;
}
// 金额转换成千分位
export function format_with_array(number) {
  // 处理前特殊值判断
  if ((typeof number == "string" && number == "-") || number == 0) {
    return number;
  }
  if (!number) return "-";
  // 转为字符串，并按照.拆分
  const arr = (number + "").split(".");
  // 整数部分再拆分
  const int = arr[0].split("");
  // 小数部分
  const fraction = arr[1] || "";
  // 返回的变量
  let r = "";
  int.reverse().forEach(function (v, i) {
    // 非第一位并且是位值是3的倍数，添加“,”
    if (i !== 0 && i % 3 === 0) {
      r = v + "," + r;
    } else {
      // 正常添加字符(这是好写法)
      r = v + r;
    }
  });
  // 整数部分和小数部分拼接
  return r + (fraction ? "." + fraction : "");
}
export const backToEntrance = (thisValue) => {
  // console.log('thisValue',thisValue);
  const rootURLS = [
    "HomeSearch",
    "FormChannel",
    "StrategyHome",
    "LineHome",
    "EveryoneHome",
    "NewHome",
    "needDealCenter",
    "workGd",
    "complaintOrderNative",
  ];

  const historyStack = thisValue.$pageStack.getStack();
  let isNeedDealCenter = false;
  let indexRoot = historyStack.findLastIndex((item) => {
    for (var url of rootURLS) {
      if (item.vnode.key.includes(url)) {
        if (item.vnode.key.includes("needDealCenter")) {
          isNeedDealCenter = true;
        }
        return true;
      }
    }
    return false;
  });
  // console.log("historyStack",historyStack)
  if (indexRoot == -1) {
    thisValue.$ydcommon.pop();
  } else {
    if (isNeedDealCenter) {
      // let regex = /^(?:\/)?needDealCenter\??$/;
      indexRoot = historyStack.findLastIndex((item) =>
        item.vnode.key.includes("/needDealCenter?")
      );
    }
    thisValue.$router.go(-(historyStack.length - indexRoot - 1));
  }
};
export const closeIconUnShow = (thisValue) => {
  const { pushType, newPushType } = thisValue.$route.query;
  if (newPushType) {
    return false;
  }
  if (pushType) {
    return pushType == "singlePage";
  }
  const rootURLS = [
    "HomeSearch",
    "FormChannel",
    "StrategyHome",
    "LineHome",
    "EveryoneHome",
    "NewHome",
  ];
  const historyStack = thisValue.$pageStack.getStack();
  if (historyStack.length > 1) {
    let item = historyStack.at(-2);
    for (var url of rootURLS) {
      if (item.vnode.key.includes(url)) {
        return true;
      }
    }
  }
  return false;
};
function splitQuery(query) {
  var queryString = query.match(/[?].*/)[0]; // [?]表示匹配第一个'?'及其之后的所有字符
  var keyValuePairs = queryString.slice(1).split("&"); // slice(1)去除开头的'?'
  var params = {};
  keyValuePairs.forEach(function (pair) {
    var parts = pair.split("="); // 通过等号分割键名和键值
    var paramName = decodeURIComponent(parts[0]); // 解码键名
    var paramValue = decodeURIComponent(parts[1]); // 解码键值
    if (params.hasOwnProperty(paramName)) {
      if (!Array.isArray(params[paramName])) {
        params[paramName] = [params[paramName]];
      }
      params[paramName].push(paramValue);
    } else {
      params[paramName] = paramValue;
    }
  });
  return params;
}
export const getCurrentStackNames = (thisValue) => {
  let routes = $vueInstance.$router.options.routes;
  return (thisValue.$store.state.global?.breadcrumbs || []).concat(
    thisValue.$pageStack.getStack().map((i) => {
      let route = i.vnode.key;
      let routePath = route.split("?")[0];
      let query = splitQuery(route);
      let name = query?.breadName || query?.themeName;
      if (!name) {
        for (let index in routes) {
          let item = routes[index];
          if (item.path && routes[index].path.indexOf(routePath) != -1) {
            name = item?.meta?.name || "默认";
            break;
          }
        }
      }
      return { name };
    })
  );
};
export const popToIndex = (thisValue, indexStack) => {
  const historyStack = (
    thisValue.$store.state.global?.breadcrumbs || []
  ).concat(thisValue.$pageStack.getStack());
  for (let index = indexStack; index < historyStack.length; index++) {
    const element = historyStack[index];
    if (element?.isApp) {
      popOriginPage(indexStack);
      return;
    }
  }
  thisValue.$router.go(-(historyStack.length - indexStack - 1));
};
// export const objectToQuery = (obj) => {
//   return Object.keys(obj)
//     .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(obj[key])}`)
//     .join('&');
// }
export const objectToQuery = (obj) => {
  return Object.keys(obj)
    .map((key) => `${key}=${obj[key]}`)
    .join("&");
};
export const removeEmptyProperties = (obj) => {
  for (let key in obj) {
    if (obj[key] === null || obj[key] === undefined || obj[key] === "") {
      delete obj[key];
    }
  }
  return obj;
};

// 业务量日清&订揽派签修改地区查询文字和表格文字
export const transformCustomProvName = (str, type, isTable) => {
  let list = [],
    strs = str.split(",");
  if (type == "1") {
    list = [
      { name: "河北", replaceName: "冀南", htmlName: "冀南" },
      { name: "北京", replaceName: "北京+冀北", htmlName: "北京\n+冀北" },
      { name: "北京冀北", replaceName: "北京+冀北", htmlName: "北京\n+冀北" },
    ];
  } else {
    list = [
      { name: "上海", replaceName: "上海+昆太", htmlName: "上海\n+昆太" },
      { name: "河北", replaceName: "冀南", htmlName: "冀南" },
      { name: "北京", replaceName: "北京+冀北", htmlName: "北京\n+冀北" },
      { name: "北京冀北", replaceName: "北京+冀北", htmlName: "北京\n+冀北" },
    ];
  }

  return strs
    .map(
      (text) =>
        (isTable
          ? list.find((obj) => obj.name == text)?.htmlName
          : list.find((obj) => obj.name == text)?.replaceName) || text
    )
    .join("、");
};

// 修复弹窗上出现弹窗层级错乱问题
export const setPopupIndex = function (selector, zIndex = 99999) {
  setTimeout(() => {
    this.$nextTick(() => {
      let dom = document.querySelectorAll(selector);
      dom.forEach((el) => {
        if (el.style.display != "none") {
          el.style.zIndex = zIndex;
        }
      });
    });
  }, 60);
};

// 将树形结构数据转为平层
export const getFlattenColumns = (treeData) => {
  let flatData = [];
  for (let i = 0; i < treeData.length; i++) {
    flatData.push({ ...treeData[i] });
    if (treeData[i].children) {
      flatData.push(...getFlattenColumns(treeData[i].children));
      delete treeData[i].children;
    }
  }
  return flatData;
};

// 取消pending中的请求
export const batchCancelHttpReq = (action = []) => {
  window.gxtAxiosPromiseArr
    ?.filter((req) => action.includes(req.action))
    .forEach((ele, index) => {
      ele.cancel();
      window.gxtAxiosPromiseArr.splice(index, 1);
    });
  window.gxtAxiosPromiseArr = [];
};

// 判断当前app版本号是否大于等于原生api需要的最低app版本号
export const checkNativeAppVersion = function (name, text) {
  let flag = true;
  const appVersion = store.state.global.appInfo.ydCommanderClientVersion
    ?.toLowerCase()
    ?.replace("v", "");
  const { platform } = Proconfig;

  if (platform != "android" && platform != "ios") {
    return true;
  }

  if (appVersion < APP_MIN_VERSION[name][platform == "ios" ? 0 : 1]) {
    flag = false;
  }

  if (!flag) {
    if (
      (platform == "ios" && appVersion >= "2.2.9") ||
      (platform == "android" && appVersion >= "3.1.3")
    ) {
      Dialog.confirm({
        message: `当前app版本不支持${
          text ? text : name + "功能"
        }，需要升级app使用`,
        confirmButtonText: "立即升级",
        cancelButtonText: "残忍拒绝",
      })
        .then(() => {
          window.yjsBridge?.call(
            "gxt.clientRegistedMethod",
            {
              actionID: 49,
            },
            () => {}
          );
        })
        .catch(() => {});
    } else {
      Dialog.alert({
        message:
          platform == "android"
            ? `当前app版本不支持${
                text ? text : name + "功能"
              }，请前往“我的”页面，点击“检查更新”进行app升级`
            : `当前app版本不支持${
                text ? text : name + "功能"
              }，请前往“我的”页面，点击“当前版本”进行app升级`,
      });
    }
    setPopupIndex.call(this, ".van-overlay", 99998);
    setPopupIndex.call(this, ".van-dialog");
  }

  return flag;
};

export const goToDownloadCenter = (context) => {
  Dialog.confirm({
    title: "导出创建成功",
    message: "文件请前往我的（页面）_下载中心进行下载。",
    confirmButtonColor: "#1678ff",
    confirmButtonText: "前往下载",
    cancelButtonText: "关闭",
  })
    .then(() => {
      context.$router.push({
        name: "DownloadCenter",
      });
    })
    .catch(() => {});
};
export const exportFileTask = (
  context,
  { action, data = null, isSetGlobalThemeCode = true }
) => {
  context.$axios
    .sendGateWay({
      action,
      data,
      isSetGlobalThemeCode,
    })
    .then((res) => {
      if (res.body && res.body.code == "SUCCESS") {
        goToDownloadCenter(context);
      } else {
        Toast.fail("导出创建失败请重试！");
      }
    })
    .catch((err) => {
      Toast.fail("导出创建失败请重试！");
    });
};
/**
 * 将数字转换为百分比并保留一位小数点
 * @param {number} value - 要转换的数字
 * @returns {string} - 转换后的百分比字符串
 */
export function toPercentage(value) {
  if (isNaN(value)) {
    throw new Error("输入值必须是一个数字");
  }
  return (value * 100).toFixed(1) + "%";
}

export const appendTokenAndTicket = (url, token, ticket) => {
  if (!url) return url;

  const urlObj = new URL(url);
  urlObj.searchParams.set("token", token);
  urlObj.searchParams.set("ticket", ticket);

  return urlObj.toString();
};

// 示例用法
const url =
  "http://u-gxt-bi.jxnq.net:30266?shareToken=eNoVjrkRBEEIA1Pif0wYIP-Qbs9StVqGFqyfmcUqmD0_Dkhtd32YuHRwAFpkC4b5QNjYxCU8GUPnY_IbLHgvAm28OLneG_NbuAQa7XlJZUeco6eJp9CyQhoT7jACvrwZKJ_EKHuAfokzGOB1EyulHFytlAulZIBltJIhL5lpEahD9-rNsEhoxecQC80aPG9acqM8tx36S-BvrqKNWkf9vSLrDtDZ9-9HUH9YDkCq#share/dashboard";
const token = "exampleToken";
const ticket = "exampleTicket";

// console.log(appendTokenAndTicket(url, token, ticket));
// 输出: http://u-gxt-bi.jxnq.net:30266?shareToken=eNoVjrkRBEEIA1Pif0wYIP-Qbs9StVqGFqyfmcUqmD0_Dkhtd32YuHRwAFpkC4b5QNjYxCU8GUPnY_IbLHgvAm28OLneG_NbuAQa7XlJZUeco6eJp9CyQhoT7jACvrwZKJ_EKHuAfokzGOB1EyulHFytlAulZIBltJIhL5lpEahD9-rNsEhoxecQC80aPG9acqM8tx36S-BvrqKNWkf9vSLrDtDZ9-9HUH9YDkCq&token=exampleToken&ticket=exampleTicket#share/dashboard

export const appendTokenAndTicketAfterShareToken = (url, token, ticket) => {
  if (!url) return url;

  const urlObj = new URL(url);
  const shareToken = urlObj.searchParams.get("shareToken");

  if (shareToken) {
    urlObj.searchParams.set("token", token);
    urlObj.searchParams.set("ticket", ticket);
  }

  return urlObj.toString();
};

// 示例用法
const url2 =
  "http://u-gxt-bi.jxnq.net:30266?shareToken=eNoVjrkRBEEIA1Pif0wYIP-Qbs9StVqGFqyfmcUqmD0_Dkhtd32YuHRwAFpkC4b5QNjYxCU8GUPnY_IbLHgvAm28OLneG_NbuAQa7XlJZUeco6eJp9CyQhoT7jACvrwZKJ_EKHuAfokzGOB1EyulHFytlAulZIBltJIhL5lpEahD9-rNsEhoxecQC80aPG9acqM8tx36S-BvrqKNWkf9vSLrDtDZ9-9HUH9YDkCq#share/dashboard";
const token2 = "exampleToken";
const ticket2 = "exampleTicket";

// console.log(appendTokenAndTicketAfterShareToken(url2, token2, ticket2));
// 输出: http://u-gxt-bi.jxnq.net:30266?shareToken=eNoVjrkRBEEIA1Pif0wYIP-Qbs9StVqGFqyfmcUqmD0_Dkhtd32YuHRwAFpkC4b5QNjYxCU8GUPnY_IbLHgvAm28OLneG_NbuAQa7XlJZUeco6eJp9CyQhoT7jACvrwZKJ_EKHuAfokzGOB1EyulHFytlAulZIBltJIhL5lpEahD9-rNsEhoxecQC80aPG9acqM8tx36S-BvrqKNWkf9vSLrDtDZ9-9HUH9YDkCq&token=exampleToken&ticket=exampleTicket#share/dashboard
